package com.lingnan.tijian.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lingnan.tijian.domain.Users;
import com.lingnan.tijian.dto.ApiResponse;
import com.lingnan.tijian.exception.TijianAPPExceptionEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;


public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入 JWT拦截器。。。。。。。。。。");
        //解析
        String token=request.getHeader("token");

        if(token!=null){
            System.out.println("开始解析JWT。。。。。。。。。。。。。。。");
            try{
                Claims  claims=Jwts.parser().setSigningKey("123456-----").parseClaimsJws(token).getBody();  //获取数据;

                Users user=new ObjectMapper().readValue((String)claims.get("currentUser"),Users.class);
                request.setAttribute("user",user);
            }catch (Exception e){
                //捕获过期异常
               e.printStackTrace();
                System.out.println("异常信息JWT拦截器输出："+e.getStackTrace());
                //返回一个json格式的ApiResponse
                ApiResponse apiResponse=new ApiResponse(TijianAPPExceptionEnum.USER_LOGIN_TIMEOUT.getCode(),TijianAPPExceptionEnum.USER_LOGIN_TIMEOUT.getMessage());

                response.getWriter().println(apiResponse.toJSONString());
                return false;
            }
        }
        return true;
    }
}
